package service;

import java.util.ArrayList;
import java.util.List;

import bean.Lucky;
import net.sf.json.JSONObject;
import utils.AppConfig;
import utils.HttpRequestVersion2;
import utils.HttpsRequest;
import action.WechatAccessTokenApi;
import dao.DepositDAOImpl;
import dao.LuckyDAOImpl;

public class DepositService {

    public static final String GET_DEPOSIT_COUNT = "http://api.weixin.qq.com/card/code/getdepositcount";
    public static final String GET_DEPOSIT_DETAIL = "https://api.weixin.qq.com/card/get";
    public static final String UPDATE_DEPOSIT_INFO = "https://api.weixin.qq.com/card/update";
    public static final String UPDATE_DEPOSIT_COUNT = "https://api.weixin.qq.com/card/modifystock";
    public static final String BUILD_NEW_DEPOSIT = "https://api.weixin.qq.com/card/create";
    public static final String SET_TEST_WHITELIST = "https://api.weixin.qq.com/card/testwhitelist/set";
    public static final String CHECK_CODE = "http://api.weixin.qq.com/card/code/checkcode";
    
    public String accessToken = "";
    // 是否已缓存
    public static boolean CACHED = false;
    
    private WechatAccessTokenApi wechatAccessTokenApi;
    private LuckyDAOImpl luckyDAOImpl;
    public DepositDAOImpl depositDAOImpl;

    public void setLuckyDAOImpl(LuckyDAOImpl luckyDAOImpl) {
        this.luckyDAOImpl = luckyDAOImpl;
    }

    public void setDepositDAOImpl(DepositDAOImpl depositDAOImpl) {
        this.depositDAOImpl = depositDAOImpl;
    }

    public void setWechatAccessTokenApi(
            WechatAccessTokenApi wechatAccessTokenApi) {
        this.wechatAccessTokenApi = wechatAccessTokenApi;
    }
    
    
    /**
     * 是否准备好发放卡券
     * 
     * @return
     */
    public boolean depositReady() {
        
        /*try {
            // 请求卡券详情
            JSONObject cardDetail = getCardDetail();
            if (cardDetail != null && cardDetail.has("cash")) {
                JSONObject cardBaseInfo = cardDetail.getJSONObject("cash")
                        .getJSONObject("base_info");
//                System.out.println("base_info = "+cardBaseInfo.toString());
                if (cardBaseInfo.has("use_custom_code")) {
//                    System.out.println("use_custom_code字段值为："+ cardBaseInfo.has("use_custom_code"));
                } else {
//                    System.out.println("没有use_custom_code字段");
//                    if(cardBaseInfo.has("sku")){
//                        JSONObject obj = cardBaseInfo.getJSONObject("sku");
//                        if(obj.has("quantity")){
//                            int quantity = obj.getInt("quantity");
//                            System.out.println("卡券库存为："+quantity);
//                            if(quantity == 0){
//                                System.out.println("更改卡券库存");
//                                //boolean result = updateCardCount();
//                            }
//                                
//                        }
//                    }                    
                    //System.out.println("更改卡券信息");
                    //boolean result = updateCardInfo();
                }
                // 向服务器请求已导入code数目
                int num = getDepositCount();
                System.out.println("已经导入的code数目为：" + num);
                if (num < Lucky.LEVEL_THIRD_COUNT) {
                    // 未全部导入，重新执行导入操作
                    System.out.println("未全部导入，重新执行导入操作");
                    //new ImportDepositThread(5000, accessToken, this).start();
                    // 通知前端尚未准备好，用四等奖（谢谢参与）代替
                    return false;
                } else if (num == Lucky.LEVEL_THIRD_COUNT) {
                    System.out.println("数目正确");
                    // 数目正确，可以发放
                    
//                    System.out.println("更改卡券库存");
//                    boolean result = updateCardCount();
                    
                    return true;
                }
            }
        } catch (Exception e) {
               e.printStackTrace();
               return false;
        }*/
                /*--------------------------以下为版本二-------------------------------*/
                //新建券(成功)
                //buildNewCard();
                //设置用户白名单
                
                //return false;
                
        return false;
    }
    
    /**
     * 导入指定数量的自定义code
     * @param count
     * @return
     */
    public void importDepositCode(int count){
        accessToken = wechatAccessTokenApi.getAccessToken();
        new ImportDepositThread(count, accessToken, this).start();
        
    }
    
    public void importDepositCode(String code){
        accessToken = wechatAccessTokenApi.getAccessToken();
        new ImportDepositThread2(code, accessToken, this).start();
    }
    
    
    
    /**
     * 获取服务端已经导入的code数目
     * 
     * @return
     */
    public int getDepositCount() {
        int num = -1;
        accessToken = wechatAccessTokenApi.getAccessToken();
        // 构造url
        String url = GET_DEPOSIT_COUNT + "?access_token=" + accessToken;
        // 构造参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("card_id", AppConfig.CARD_ID);
        // 获取返回结果
        String response = null;
        try {
            response = HttpRequestVersion2.httpPost(url, jsonParam).toString();
        } catch (Exception e) {
            response = null;
        }
        // 处理返回结果
        if (response == null) {
            // 获取失败
            num = -1;
        } else {
            // 解析返回数据
            System.out.println("在getDepositCount（）方法中服务器返回的结果为："+ response.toString());
            JSONObject obj = JSONObject.fromObject(response);
            if (obj.has("errcode") && obj.getInt("errcode") == 0 && obj.has("count")) {
                num = obj.getInt("count");
            }else if(obj.getInt("errcode") == 40001){
                accessToken = wechatAccessTokenApi.getAccessTokenFromWechatServer();
                num = getDepositCount();
            }
        }
        return num;
    }
    
    
    /**
     * 获取卡券详情
     * 
     * @return
     */
    public JSONObject getCardDetail() {

        JSONObject jsonObject = null;

        accessToken = wechatAccessTokenApi.getAccessToken();
        // 构造url
        String url = GET_DEPOSIT_DETAIL + "?access_token=" + accessToken;
//        System.out.println("getCardDetail（）方法申请访问的url为:" + url);
        // 构造参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("card_id", AppConfig.CARD_ID2);
        System.out.println("card id=："+AppConfig.CARD_ID2);

        try {
            // 获取返回结果
            jsonObject = HttpRequestVersion2.httpPost(url, jsonParam);
            if (jsonObject != null) {
                //System.out.println("返回卡券详情接口返回的数据为：" + jsonObject.toString());

                if (jsonObject.has("errcode")
                        && jsonObject.getInt("errcode") == 0
                        && jsonObject.has("card")) {
                    jsonObject = jsonObject.getJSONObject("card");

                }else if(jsonObject.getInt("errcode") == 40001){
                    //access_token 过期，重新获取
                    accessToken = wechatAccessTokenApi.getAccessTokenFromWechatServer();
                    getCardDetail();
                    
                }else
                    jsonObject = null;
            }

        } catch (Exception e) {
            jsonObject = null;
            System.out.println("发生异常");
        }

        return jsonObject;
    }
    
    /**
     * 新建卡券
     */
    public void buildNewCard(){
        
        String result = "";
        
        accessToken = wechatAccessTokenApi.getAccessToken();
        // 构造url
        String url = BUILD_NEW_DEPOSIT + "?access_token=" + accessToken;
        // 构造参数
        JSONObject jsonParams = JSONObject.fromObject(AppConfig.CARD_INFO2);
        System.out.println("发送参数为：" + jsonParams.toString());

        try {
            // 获取返回结果
            result = HttpsRequest.sendPost(url, jsonParams.toString());
            if (result != null) {
                System.out.println("新建卡券返回的数据为：" + result);
                JSONObject obj = JSONObject.fromObject(result);
                if (obj.has("errcode") && obj.getInt("errcode") == 0) {
                    System.out.println("更新成功");
                }
            }

        } catch (Exception e) {
            System.out.println("发生异常");
            e.printStackTrace();
        }

    }
    
    /**
     * 修改卡券库存
     * @return
     */
    public boolean updateCardCount(){
        String result = null;

        accessToken = wechatAccessTokenApi.getAccessToken();
        // 构造url
        String url = UPDATE_DEPOSIT_COUNT + "?access_token=" + accessToken;
        // 构造参数
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("card_id", AppConfig.CARD_ID2);
        jsonParams.put("increase_stock_value", 5000);
//        jsonParams.put("reduce_stock_value", 5000);
        System.out.println("发送参数为：" + jsonParams.toString());

        try {
            // 获取返回结果
            result = HttpsRequest.sendPost(url, jsonParams.toString());
            if (result != null) {
                System.out.println("修改卡券库存返回的数据为：" + result);
                JSONObject obj = JSONObject.fromObject(result);
                if (obj.has("errcode") && obj.getInt("errcode") == 0) {
                    System.out.println("更新成功");
                    return true;
                }
            }

        } catch (Exception e) {
            System.out.println("发生异常");
            e.printStackTrace();
        }

        return false;
    }
    
    /**
     * 更新卡券信息
     * 
     * @return
     */
    public boolean updateCardInfo() {
        String result = null;

        accessToken = wechatAccessTokenApi.getAccessToken();
        // 构造url
        String url = UPDATE_DEPOSIT_INFO + "?access_token=" + accessToken;
        // 构造参数
        JSONObject jsonParams = new JSONObject();
        JSONObject objCash = new JSONObject();
        JSONObject objBaseInfo = new JSONObject();
//        objBaseInfo.put("bind_openid", false); //是否指定只有指定openid才能领取卡券
        objBaseInfo.put("custom_url_name", "劲牌商城"); //指定自定义入口名称
//        objBaseInfo.put("custom_url", "http://www.jingpai.com/"); //指定自定义入口网址
        objBaseInfo.put("custom_url_sub_title", "使用此代金券"); //指定自定义入口右侧提示语
        objCash.put("base_info", objBaseInfo);
        jsonParams.put("cash", objCash);
        jsonParams.put("card_id", AppConfig.CARD_ID);
        System.out.println("发送参数为：" + jsonParams.toString());

        try {
            // 获取返回结果
            result = HttpsRequest.sendPost(url, jsonParams.toString());
            if (result != null) {
                System.out.println("更新卡券详情接口返回的数据为：" + result);
                JSONObject obj = JSONObject.fromObject(result);
                if (obj.has("errcode") && obj.getInt("errcode") == 0) {
                    System.out.println("更新成功");
                    return true;
                }else if(obj.getInt("errcode") == 40001){
                    //access_token 过期，重新获取
                    accessToken = wechatAccessTokenApi.getAccessTokenFromWechatServer();
                    updateCardInfo();
                    
                }else{}
            }

        } catch (Exception e) {
            System.out.println("发生异常");
            e.printStackTrace();
        }

        return false;
    }
    
    /**
     * 获取下一个三等奖的卡券code
     * @param type 0-card1 1-card2
     * @return
     */
    public String getNextCode(int type){
        int num = luckyDAOImpl.getCountByType(type);        
        System.out.println("目前 type="+type+"的人数为："+num);
        String code = depositDAOImpl.getNextCode(type, num);
        System.out.println("下一个编码为："+code);
        return code;
    }
    
    /**
     * 设置测试白名单
     */
    public void setTestWhiteList(){
        String result = "";
        accessToken = wechatAccessTokenApi.getAccessTokenFromWechatServer();
        // 构造url
        String url = SET_TEST_WHITELIST + "?access_token=" + accessToken;
        //添加白名单
        List<String> whiteList = new ArrayList<String>();
        whiteList.add("\"ol-ZLt9k_FArQx5fpP9svPCzjCGw\"");
        whiteList.add("\"ol-ZLt42QCylIQbUXxUsUFEAvVCU\"");
        System.out.println("测试白名单为："+whiteList.toString());
        // 构造参数
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("openid", whiteList.toString());
        System.out.println("发送参数为：" + jsonParams.toString());

        try {
            // 获取返回结果
            result = HttpsRequest.sendPost(url, jsonParams.toString());
            if (result != null) {
                System.out.println("设置白名单接口返回的数据为：" + result);
                JSONObject obj = JSONObject.fromObject(result);
                if (obj.has("errcode") && obj.getInt("errcode") == 0) {
                    System.out.println("更新成功");
                }
            }

        } catch (Exception e) {
            System.out.println("发生异常");
            e.printStackTrace();
        }
    }
    
    public void checkCode(){

        JSONObject jsonObject = null;

        accessToken = wechatAccessTokenApi.getAccessToken();
        // 构造url
        String url = CHECK_CODE + "?access_token=" + accessToken;
        //添加待检查code
        List<String> codeList = new ArrayList<String>();
        codeList.add("\"B0099A0200001\"");
        codeList.add("\"B0099A0200002\"");
        // 构造参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("card_id", AppConfig.CARD_ID);
        jsonParam.put("code", codeList.toString());

        try {
            // 获取返回结果
            jsonObject = HttpRequestVersion2.httpPost(url, jsonParam);
            if (jsonObject != null) {
                System.out.println("核查code接口返回的数据为：" + jsonObject.toString());
                if (jsonObject.has("errcode")&& jsonObject.getInt("errcode") == 0) {
                    

                }else if(jsonObject.getInt("errcode") == 40001){
                    //access_token 过期，重新获取
                    accessToken = wechatAccessTokenApi.getAccessTokenFromWechatServer();
                    checkCode();
                    
                }else{}
            }

        } catch (Exception e) {
            jsonObject = null;
            System.out.println("发生异常");
        }
        
    }
    
}


class ImportDepositThread extends Thread {
    private int importCount = 0;
    private String token = "";
    private DepositService depositService;

    public ImportDepositThread(int importCount, String token, DepositService depositService) {
        this.importCount = importCount;
        this.token = token;
        this.depositService = depositService;
    }

    public void run() {
        // 执行导入操作，每次导入上限为100个
        System.out.println("ImportDepositThread 中 access_token为:" + token);
        // 构造url
        String url = "http://api.weixin.qq.com/card/code/deposit?access_token="
                + token;
        System.out.println("导入code方法申请访问的url为:" + url);
        int count = importCount / 100;
        System.out.println("code需要分" + count + "次导入");
        for (int i = 0; i < count; i++) {
            System.out.println("第"+i+"次");
            // 从本地数据库读取要导入的code
            String codes = depositService.depositDAOImpl.getCodes(i * 100 + 1, i * 100 + 100);
            // 构造参数
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("card_id", AppConfig.CARD_ID2);
            jsonParams.put("code", codes);
            // 获取返回结果
            String response = null;
            try {
                response = HttpRequestVersion2.httpPost(url, jsonParams)
                        .toString();
            } catch (Exception e) {
                response = null;
            }
            // 处理返回结果
            if (response == null) {
                // 获取失败
            } else {
                // 解析返回数据
                System.out.println("导入code()方法中服务器返回的结果为："
                        + response.toString());
                JSONObject obj = JSONObject.fromObject(response);
                if (obj.has("errcode") && obj.getInt("errcode") == 0) {

                } else {
                    break;
                }
            }
        }

    }
}

class ImportDepositThread2 extends Thread {
    private String token = "";
    private DepositService depositService;
    private String code;

    public ImportDepositThread2(String code, String token, DepositService depositService) {
        this.code = code;
        this.depositService = depositService;
        this.token = token;
    }

    public void run() {

        String url = "http://api.weixin.qq.com/card/code/deposit?access_token="
                + token;

            // 从本地数据库读取要导入的code
            String codes = "[\""+code+"\"]";
            // 构造参数
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("card_id", AppConfig.CARD_ID2);
            jsonParams.put("code", codes);
            // 获取返回结果
            String response = null;
            try {
                response = HttpRequestVersion2.httpPost(url, jsonParams)
                        .toString();
            } catch (Exception e) {
                response = null;
            }
            // 处理返回结果
            if (response == null) {
                // 获取失败
            } else {
                // 解析返回数据
                System.out.println("导入code()方法中服务器返回的结果为："
                        + response.toString());
                JSONObject obj = JSONObject.fromObject(response);
                if (obj.has("errcode") && obj.getInt("errcode") == 0) {

                } else {
                   
                }
            }

    }
}

